package t4tools.lepath.generate.visitor;

import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;

import t4tools.lepath.model.Clazz;
import t4tools.lepath.model.Field;

public class FieldReader extends FieldVisitor {
	public static final String FIELD_GETTER_ANNOTATION_DESCR = Type.getType(t4tools.lepath.annotations.Field.class).getDescriptor();

	private Field field;
	private Clazz clazz;

	public FieldReader(Clazz clazz, Field field) {
		super(Opcodes.ASM4);
		this.field = field;
		this.clazz = clazz;
	}

	private class FieldAnnotationVisitor extends AnnotationVisitor {

		public FieldAnnotationVisitor() {
			super(Opcodes.ASM4);
		}

		@Override
		public void visit(String name, Object value) {
			if ("property".equals(name)) {
				getField().setName((String) value);
			} else if ("getter".equals(name)) {
				getField().setGetter((String) value);
			}
		}
	}

	@Override
	public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
		if (FIELD_GETTER_ANNOTATION_DESCR.equals(desc)) {
			return new FieldAnnotationVisitor();
		}
		return super.visitAnnotation(desc, visible);
	}

	public Field getField() {
		return field;
	}

	public void setField(Field field) {
		this.field = field;
	}

	public Clazz getClazz() {
		return clazz;
	}

	public void setClazz(Clazz clazz) {
		this.clazz = clazz;
	}
}
